<template>
  <Card title="统计分析">
    <div class="chart">
      <BarChart :chartData="bookTypeNum" v-if="bookTypeNum.length" />
      <PieChart :chartData="bookTypeNum" v-if="bookTypeNum.length" />
      <div v-else class="loading">加载中...</div>
    </div>
  </Card>
</template>

<script setup>
import { getBookTypeNum } from "@/api/analyse";
import { onMounted, ref, watch } from "vue";
import BarChart from "./pictures/BarChart.vue";
import PieChart from "./pictures/PieChart.vue";

const bookTypeNum = ref([]);

// 获取图书类型数据
const getBookType = async () => {
  try {
    const res = await getBookTypeNum();

    // 确保数据格式正确：数组，每个元素有name和value属性
    bookTypeNum.value = res.data.data.map((item) => ({
      name: item.name || item.type || "未知",
      value: item.value || item.count || 0,
    }));
    console.log("获取到的数据:", bookTypeNum.value);
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

onMounted(() => {
  getBookType();
});
</script>

<style scoped>
.chart {
  width: 100%;
  min-height: 400px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  gap: 20px;
}

.loading {
  width: 100%;
  text-align: center;
  padding: 20px;
}
</style>
